<?php

namespace app\modules\user\service;

use Yii;
use app\common\behaviors\ApiCommonBehavior;
use app\common\base\ApiService;
use app\modules\user\models\Account;
use DateTime;
use Exception;
use PhpOffice\PhpSpreadsheet\Shared\Date;

class AccountService extends ApiService
{
    const PASSWORD_PREFIX = 'web-back-end';

    function __construct()
    {
        parent::init();
        $this->model = new Account();
    }


    /**
     * 登录;
     * 返回的信息包括token，用来在不同模块间传递加密信息，识别身份;
     * 
     * @param int $userId 用户名
     * @param string $password 密码
     * @return array 各种信息，包括token
     */
    public function login($userId, $password, $type)
    {
        $info = $this->info([
            'condition' => [
                'username' => $userId,
                'status' => 1,
                'type' => $type,
            ],
        ]);
        if(empty($info)) {
            return ApiCommonBehavior::error('ERROR_INVALID_USERID', '用户不存在');
        }

        if($this->buildPassword($password) != $info['pwd']) {
            return ApiCommonBehavior::error('ERROR_INVALID_PASSWORD', '密码不正确');
        }
        unset($info['pwd']);
        
        $token = $this->getToken($info);
       
        return [
            'info' => $info,
            'token' => $token,
        ];
    }

    /**
     * 注册;
     * 返回的信息为账户id等信息;
     * 
     * 
     * @param string $nickname 昵称
     * @param string $pwd 密码
     * @param int $type 用户类型
     * @param string $email 邮箱(可选)
     * @return array 成功返回账号的信息，失败返回['id' => null]
     */
    public function register($username, $nickname, $pwd, $type, $email = null){
        try{
            $uid = $this->add([
                'username' => $username,
                'nickname' => $nickname,
                'pwd' => $this->buildPassword($pwd),
                'type' => $type,
                'email' => $email,
                'status' => 1,
            ]);
        }catch(Exception $e){
            return ApiCommonBehavior::error('ERROR_DUPLICATE_USERNAME', '用户名重复');
        }
        

        if(empty($uid)){
            return [
                'id' => $uid,
            ];
        }

        return [
            'id' => $uid,
            'username' => $username,
            'nickname' => $nickname,
            'type' => $type,
            'email' => $email,
        ];
    }






    /**
     * 密码加密;
     * 
     * @return string 加密后的密码
     */
    public function buildPassword($password)
    {
        return base64_encode(self::PASSWORD_PREFIX . $password);
    }
 
    /**
     * 生成用户token;
     * 
     * @return string token
     */
    public function getToken($info)
    {
        $token = Yii::$app->jwt->createToken([
            'id' => $info['id'],
            'username' => $info['username'],
            'type' => $info['type']
        ]);
        return $token;
    }
}

